import requests
import json
import os
import time


def clear_screen():
    # 清除终端屏幕
    os.system("cls" if os.name == "nt" else "clear")


def status():
    # 获取当前登录状态
    url = "http://192.168.96.110/api/account/status"
    try:
        response = requests.get(url, timeout=5)
        return response
    except requests.exceptions.RequestException as e:
        print(f"获取状态时发生网络错误: {e}")
        return None


def login(username, password):
    # 使用给定的用户名和密码进行登录
    url = "http://192.168.96.110/api/account/login"
    data = {"username": username, "password": password, "nasld": "2"}
    try:
        response = requests.post(url, data=data, timeout=5)
        return response
    except requests.exceptions.RequestException as e:
        print(f"登录时发生网络错误: {e}")
        return None


def logout():
    # 登出当前用户
    url = "http://192.168.96.110/api/account/logout"
    try:
        response = requests.get(url, timeout=5)
        return response
    except requests.exceptions.RequestException as e:
        print(f"登出时发生网络错误: {e}")
        return None


def create_config():
    # 创建配置文件，用户输入学号和密码
    config_list = []
    while True:
        username = input("请输入你的学号(输入q退出):")
        if username == "q":
            print("您共创建了{}个账号".format(len(config_list)))
            break
        password = input("请输入身份证后8位:")
        try:
            assert username.isdigit() and password.isdigit(), "账号密码必须是数字"
            config_list.append({"username": username, "password": password})
        except AssertionError as e:
            print(e)
    with open("config.json", "w") as f:
        json.dump(config_list, f)


def load_config():
    # 加载配置文件
    try:
        with open("config.json", "r") as f:
            config_list = json.load(f)
            if not isinstance(config_list, list):
                print("配置文件格式错误，请重新创建")
                create_config()
                return load_config()
    except FileNotFoundError:
        print("未找到配置文件,请先创建")
        create_config()
        return load_config()
    return config_list


def handle_login(config_list):
    # 处理登录逻辑
    try:
        status_response = status()
        if status_response is None:
            return {"code": 1, "msg": "网络错误"}

        try:
            status_json = json.loads(status_response.text)
        except json.JSONDecodeError as e:
            print(f"解析状态信息时出错: {e}")
            return {"code": 1, "msg": "JSON解析错误"}

        for config in config_list:
            if not isinstance(config, dict):
                print("配置文件格式错误，请重新创建")
                create_config()
                return handle_login(load_config())

            try:
                username = config["username"]
                password = config["password"]
            except KeyError as e:
                print(f"配置文件缺少必要字段: {e}")
                continue

            if status_json["code"] == 1:
                login_response = login(username, password)
                if login_response is None:
                    continue

                try:
                    login_json = json.loads(login_response.text)
                except json.JSONDecodeError as e:
                    print(f"解析登录信息时出错: {e}")
                    continue

                if login_json["code"] == 1:
                    print("账号或密码错误, 尝试下一个账号")
                    continue
                elif login_json["code"] == 2:
                    print("需要填写验证码，请前往 http://192.168.96.110/ 登录")
                    return {"code": 2, "msg": "需要验证码"}

                status_response = status()
                if status_response is None:
                    continue

                try:
                    status_json = json.loads(status_response.text)
                except json.JSONDecodeError as e:
                    print(f"解析状态信息时出错: {e}")
                    continue

                if status_json["dialMsg"] != "已拨号成功":
                    print("登录失败, 尝试下一个账号")
                    continue
                else:
                    break
        return status_json
    except Exception as e:
        print(f"登录过程中发生未预期的错误: {e}")
        return {"code": 1, "msg": f"未预期错误: {str(e)}"}


def display_status(status_json):
    # 显示登录状态
    clear_screen()
    try:
        if "online" in status_json and status_json["online"]:
            print("您好, {}".format(status_json["online"].get("Name", "未知用户")))
            print("当前账号: {}".format(status_json["online"].get("Username", "未知")))
            print("当前IP: {}".format(status_json["online"].get("UserIpv4", "未知")))
            print("当前MAC: {}".format(status_json["online"].get("UserMac", "未知")))
            print("登录状态：{}".format(status_json.get("dialMsg", "未知")))
        else:
            print("未获取到用户信息")
        print("登录状态：{}".format(status_json.get("dialMsg", "未知")))
        print("==============================================================")
    except Exception as e:
        print(f"显示状态信息时出错: {e}")
        print("==============================================================")


def handle_user_input():
    # 处理用户输入
    try:
        user_input = input(
            "0.退出登录\n1.修改账号配置\n2.关闭软件但不断开连接\n请选择: "
        )
        try:
            flag = int(user_input)
            if flag == 0:
                logout_response = logout()
                if logout_response is not None:
                    print("已成功登出")
                return False
            elif flag == 1:
                create_config()
                logout_response = logout()
                if logout_response is not None:
                    print("已成功登出")
                return True
            elif flag == 2:
                print("正在退出程序...")
                exit()
            else:
                print("无效的选项，请重新选择")
            return True
        except ValueError:
            print("请输入有效的数字选项")
            return True
    except Exception as e:
        print(f"处理用户输入时出错: {e}")
        return True


def main():
    try:
        config_list = load_config()
        while True:
            try:
                status_json = handle_login(config_list)
                if status_json and "code" in status_json and status_json["code"] != 1:
                    display_status(status_json)
                    if not handle_user_input():
                        break
                else:
                    clear_screen()
                    print("当前未登录或登录状态异常，尝试重新登录...")
            except Exception as e:
                print(f"主循环中发生错误: {e}")
                print("5秒后重试...")
                time.sleep(5)
    except KeyboardInterrupt:
        print("\n程序被用户中断")
    except Exception as e:
        print(f"程序发生严重错误: {e}")
    finally:
        print("程序已退出")


if __name__ == "__main__":
    main()
